package com.gxpt.app.view;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.bean.goodsdetail_bean;
import com.gxpt.app.bean.normal;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_webview)
public class Activity_webview extends BaseActivity {

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.mWebView)
    WebView mWebView;

    String url="";//url
    Bundle d;
    String ID = "";

    String shop_id    = "";
    String sell_price = "";
    int    buy_num    = 0;
    String sku_id     = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);

        d  = getIntent().getBundleExtra("DATA");
        if(d!=null){
            ID = d.getString("ID");
        }
        initView();
        initData();
    }

    @Override
    public void initView() {

        txt_title.setText(getResources().getString(R.string.txt_goods_detail));


        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setBuiltInZoomControls(true);
        settings.setSupportZoom(true);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        mWebView.requestFocus();
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.setHorizontalScrollBarEnabled(false);//水平不显示
        mWebView.setVerticalScrollBarEnabled(false); //垂直不显示
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        mWebView.setWebViewClient(new WebViewClient(){

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon){
                hud.show();

            }
            public void onPageFinished(WebView view, String url){
                try{
                    if(hud.isShowing()){
                        hud.dismiss();
                    }
                }catch(Exception e){
                    e.printStackTrace();
                    hud.dismiss();
                }


            }

            public boolean shouldOverrideUrlLoading(WebView view, String backurl){
                Logger.i("url = "+backurl);
                if(backurl.indexOf("buy")>=0){//添加购物车

                    Dialog_detail();
                }
                return true;
            }
        });

        url = Constant.URL_H5_goods_detail+ID;

        Logger.i("url = "+url);
        mWebView.loadUrl(url);
    }

    @Override
    public void initData() {
        toNet_demanddetail();
    }



    @Event(value={R.id.toback})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
        }
    }

    TextView    txt_sell_price;
    TextView    txt_buy_num;
    TextView    txt_sku_name;
    GridLayout  GL_gk;
    List<goodsdetail_bean.skus> mskus;
    int current_stock = 0;
    public void Dialog_detail(){
        sku_id = "";
        final Dialog dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_goods_detail, null);
        dialog.setContentView(view);
        txt_buy_num = (TextView)view.findViewById(R.id.txt_buy_num);
        txt_sku_name = (TextView)view.findViewById(R.id.txt_sku_name);
        GL_gk       = (GridLayout)view.findViewById(R.id.GL_gk);
        ImageView img_close = (ImageView)view.findViewById(R.id.img_close);
        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        TextView txt_add = (TextView)view.findViewById(R.id.txt_add);
        txt_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!sku_id.isEmpty()){
                    if((buy_num + 1)<=current_stock){
                        buy_num++;
                        txt_buy_num.setText(""+buy_num);
                    }else {
                        T.show(context,""+getResources().getString(R.string.alert_stock_isnot),1);
                    }
                }else {
                    T.show(context,""+getResources().getString(R.string.alert_guige_isnot),1);
                }



             }
        });
        TextView txt_jian = (TextView)view.findViewById(R.id.txt_jian);
        txt_jian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(buy_num>1){
                    buy_num--;
                }
                txt_buy_num.setText(""+buy_num);

            }
        });
        txt_sell_price = (TextView)view.findViewById(R.id.txt_sell_price);
        txt_sell_price.append(sell_price);


        if(mskus != null){
            if(mskus.size()>0){
                for(goodsdetail_bean.skus d:mskus){
//                    Logger.i(""+d.sku_name);
                    GL_gk.addView(creatListItemView(d,Integer.parseInt(d.sku_id)));
                }
            }
        }
        Button toSure = (Button)view.findViewById(R.id.toSure);
        toSure.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                if(!sku_id.isEmpty() && buy_num > 0){
                    dialog.dismiss();
                    toNet_addtocart();
                }else{
                    T.show(context,""+getResources().getString(R.string.alert_guige_isnot2),1);
                }
            }
        });

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }

    private View creatListItemView(goodsdetail_bean.skus d, int id) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_goods_sku, null);

        TextView t_sku_name = (TextView)convertView.findViewById(R.id.t_sku_name);
        TextView t_sku_id   = (TextView)convertView.findViewById(R.id.t_sku_id);
        TextView t_stock    = (TextView)convertView.findViewById(R.id.t_stock);

        t_sku_name.setText(d.sku_name);
        t_sku_id.setText(d.sku_id);
        t_stock.setText(d.stock);

        convertView.setId(id);
        convertView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                int ViewID = v.getId();

                TextView t_sku_name = (TextView)v.findViewById(R.id.t_sku_name);
                TextView t_sku_id   = (TextView)v.findViewById(R.id.t_sku_id);
                TextView t_stock    = (TextView)v.findViewById(R.id.t_stock);
                t_sku_name.setBackgroundResource(R.drawable.kuang_red_red_style2);
                txt_sku_name .setText(t_sku_name.getText().toString());
                sku_id       = t_sku_id.getText().toString();

                current_stock = Integer.parseInt(t_stock.getText().toString());

                buy_num = 0;
                txt_buy_num.setText(""+buy_num);

                for(int a=0;a<GL_gk.getChildCount();a++){
                    if(GL_gk.getChildAt(a).getId()!=ViewID){
                        TextView skuName = (TextView)GL_gk.getChildAt(a).findViewById(R.id.t_sku_name);
                        skuName.setBackgroundResource(R.drawable.kuang_huise_huise_style2);
                    }
                }

//                main_id   = ""+ViewID;
//                main_name = ""+list_title.getText().toString();

            }
        });
        return convertView;
    }

    private void setData(goodsdetail_bean.goodsdetail_data data){
        sell_price = data.goodsdetail.sell_price;
        mskus      = data.skuinfo;
        shop_id    = data.goodsdetail.shop_id;
    }

    //////NET DO
    StringCallback do_goodsdetail = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(s);
            try{
                goodsdetail_bean data = new Gson().fromJson(s, goodsdetail_bean.class);

                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    setData(data.data);
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

    //    /////NET
    private void toNet_demanddetail(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shop");
            jsonBody.put("serviceName",          "goodsdetail");

            jsonBody.put("id",                   ID);


        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i(jsonBody.toString()+" ==["+Constant.URL_goodsdetail+" ]");
        HttpUtils.http_post_string(Constant.URL_goodsdetail,jsonBody.toString(),do_goodsdetail);
    }



    private void toNet_addtocart(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            //1
            JSONObject jsonBody2=new JSONObject();
            jsonBody2.put("goods_id"  ,ID);
            jsonBody2.put("sku_id"    ,sku_id);
            jsonBody2.put("shop_id"   ,shop_id);
            jsonBody2.put("buy_num"   ,buy_num);
            //2
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shopcart");
            jsonBody.put("serviceName",          "addtocart");

            jsonBody.put("member_id",            AppUtils.get_user_id(context));
            jsonBody.put("goods",                 jsonBody2);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.i(jsonBody.toString()+" ==["+Constant.URL_addtocart+" ]");
        HttpUtils.http_post_string(Constant.URL_addtocart,jsonBody.toString(),do_addtocart);
    }

    StringCallback do_addtocart = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(s);
            try{
                normal data = new Gson().fromJson(s, normal.class);

                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    T.show(context,""+getResources().getString(R.string.alert_success_do),1);
                    EventBus.getDefault().post(new MessageEvent(Constant.ACTION_to_shopping_refresh));
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
}
